<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-06-28
 */

namespace weapp\Verify\controller;

use think\Db;
use think\Page;
use app\common\controller\Weapp;
use weapp\Verify\model\VerifyModel;
use weapp\Verify\logic\VerifyLogic;

/**
 * 插件的控制器
 */
class Verify extends Weapp
{
    // 构造方法
    public function __construct() {
        parent::__construct();
        // 当前时间戳
        $this->times = getTime();
        // 模型层
        $this->model = new VerifyModel;
        // 业务层
        $this->logic = new VerifyLogic;
        // 核销信息表
        $this->region_db = Db::name('region');
        $this->verify_db = Db::name('weapp_verify');
        $this->verify_store_db = Db::name('weapp_verify_store');
        $this->verify_staff_db = Db::name('weapp_verify_staff');
        // 订单信息
        $this->order_db = Db::name('shop_order');
        $this->order_details_db = Db::name('shop_order_details');
        // 插件基本信息
        $this->weappInfo = $this->getWeappInfo();
        $this->assign('weappInfo', $this->weappInfo);
        // 处理插件配置
        $this->data = Db::name('weapp')->where('code', $this->weappInfo['code'])->getField('data');
        if (!empty($this->data)) {
            $this->data = unserialize($this->data);
        } else {
            $this->data = [];
            $this->saveConfig(0, false);
        }
        $this->assign('data', $this->data);
    }

    // 插件安装的后置操作
    public function afterInstall()
    {
        if (!empty($this->weappInfo)) {
            // 数据前缀
            $prefix = config('database.prefix');
            // 文档表字段处理
            $this->logic->addArchivesTableHandle($prefix);
            // 订单表字段处理
            $this->logic->addShopOrderTableHandle($prefix);
        }
    }

    // 插件卸载的后置操作
    public function afterUninstall()
    {
        if (!empty($this->weappInfo)) {
            // 数据前缀
            $prefix = config('database.prefix');
            // 关闭核销功能则将下架所有核销相关的商品
            $this->closeVerifyGoods(0);
            // 文档表字段处理 -- 目前废弃，后续新版本再去掉
            // $this->logic->delArchivesTableHandle($prefix);
            // 订单表字段处理 -- 目前废弃，后续新版本再去掉
            // $this->logic->delShopOrderTableHandle($prefix);
        }
    }

    // 插件禁用的后置操作
    public function afterDisable()
    {
        // 关闭核销功能则将下架所有核销相关的商品
        $this->closeVerifyGoods(0);
    }

    // 核销功能设置
    public function config()
    {
        if (IS_AJAX_POST) {
            $openVerify = input('post.openVerify/d', 0);
            // 关闭核销功能则将下架所有核销相关的商品
            $this->closeVerifyGoods($openVerify);
            // 保存配置
            $this->saveConfig($openVerify, true);
            
        }

        return $this->fetch();
    }

    // 一键上架所有核销相关商品 --- 暂不使用
    public function openVerifyGoods()
    {
        if (IS_AJAX_POST && 1 === intval($this->data['openVerify'])) {
            // $where = [
            //     'prom_type' => 0,
            //     'logistics_type' => ['IN', ['2', '1,2']]
            // ];
            // $update = [
            //     // 'status' => 1,
            //     'arcrank' => 0,
            //     'update_time' => getTime(),
            // ];
            // Db::name('archives')->where($where)->update($update);
            // $this->success('一键上架成功');
        }
        // $this->error('请先开启核销功能');
    }

    // 关闭核销功能则将下架所有核销相关的商品 --- 暂不使用
    private function closeVerifyGoods($openVerify = 1)
    {
        if (0 === intval($openVerify) && 1 === intval($this->data['openVerify'])) {
            // // 关闭核销功能则将下架所有核销相关的商品
            // $where = [
            //     'prom_type' => 0,
            //     'logistics_type' => ['IN', ['2']]
            // ];
            // $update = [
            //     // 'status' => 0,
            //     'arcrank' => -1,
            //     'update_time' => getTime(),
            // ];
            // Db::name('archives')->where($where)->update($update);
        }
    }

    // 保存配置
    private function saveConfig($openVerify = 0, $return = true)
    {
        // 商品核销
        $this->data['openVerify'] = intval($openVerify);
        // 后台二次核销
        $openSecondVerify = input('post.openSecondVerify/d', 0);
        if (isset($openSecondVerify)) $this->data['openSecondVerify'] = intval($openSecondVerify);
        // 更新插件设置数据
        $update = [
            'data' => serialize($this->data),
            'update_time' => getTime()
        ];
        $result = Db::name('weapp')->where('code', $this->weappInfo['code'])->update($update);
        if (!empty($return)) {
            if (!empty($result)) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
    }

    // 核销门店列表
    public function verify_store()
    {
        // 查询条件
        $where = [];
        $param = input('param.');
        if (!empty($param['store_status'])) $where['store_status'] = intval($param['store_status']);
        if (!empty($param['keywords'])) $where['store_name|store_phone'] = ['like', "%{$param['keywords']}%"];

        // 查询门店
        $count = $this->verify_store_db->where($where)->count();
        $pageObj = new Page($count, config('paginate.list_rows'));
        $store = $this->verify_store_db->where($where)->order('store_id desc')->limit($pageObj->firstRow . ',' . $pageObj->listRows)->select();

        // 加载数据
        $this->assign('store', $store);
        $this->assign('pageObj', $pageObj);
        $this->assign('pageStr', $pageObj->show());
        return $this->fetch();
    }

    // 核销门店列表
    public function verify_store_add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 数据验证
            $validate = [
                ['field' => 'store_name', 'name' => '请输入门店名称'],
                ['field' => 'store_phone', 'name' => '请输入门店手机'],
                ['field' => 'store_address', 'name' => '请输入详细地址'],
                ['field' => 'store_business', 'name' => '请选择营业时间'],
                ['field' => 'store_point', 'name' => '请选择图片位置'],
            ];
            $this->validatePost($validate, $post);

            // 添加门店
            $storePoint = explode(',', $post['store_point']);
            $insert = [
                'store_name' => $post['store_name'],
                'store_phone' => $post['store_phone'],
                'store_status' => 1,
                'store_province' => !empty($post['store_province']) ? intval($post['store_province']) : 1,
                'store_city' => !empty($post['store_city']) ? intval($post['store_city']) : 2,
                'store_area' => !empty($post['store_area']) ? intval($post['store_area']) : 3,
                'store_address' => $post['store_address'],
                'store_business' => $post['store_business'],
                'store_logo' => !empty($post['store_logo']) ? $post['store_logo'] : '',
                'store_coverpic' => !empty($post['store_coverpic']) ? $post['store_coverpic'] : '',
                'store_latitude' => !empty($storePoint[1]) ? $storePoint[1] : '',
                'store_longitude' => !empty($storePoint[0]) ? $storePoint[0] : '',
                'store_intro' => !empty($post['store_intro']) ? $post['store_intro'] : '',
                'add_time' => $this->times,
                'update_time' => $this->times,
            ];
            $result = $this->verify_store_db->insert($insert);
            if (!empty($result)) {
                $this->success('添加成功', weapp_url('Verify/Verify/verify_store'));
            } else {
                $this->error('添加失败');
            }
        }

        $this->assign('provinceList', get_province_list());
        return $this->fetch();
    }

    // 核销门店列表
    public function verify_store_edit()
    {
        $store_id = input('param.store_id/d', 0);
        $validate = [
            ['field' => 'store_id', 'name' => '请选择编辑的门店'],
        ];
        $this->validatePost($validate, ['store_id'=>$store_id]);

        // 查询条件
        $where = [
            'store_id' => $store_id
        ];

        if (IS_AJAX_POST) {
            $post = input('post.');
            // 数据验证
            $validate = [
                ['field' => 'store_name', 'name' => '请输入门店名称'],
                ['field' => 'store_phone', 'name' => '请输入门店手机'],
                ['field' => 'store_address', 'name' => '请输入详细地址'],
                ['field' => 'store_business', 'name' => '请选择营业时间'],
                ['field' => 'store_point', 'name' => '请选择图片位置'],
            ];
            $this->validatePost($validate, $post);

            // 编辑门店
            $storePoint = explode(',', $post['store_point']);
            $update = [
                'store_name' => $post['store_name'],
                'store_phone' => $post['store_phone'],
                'store_status' => !empty($post['store_status']) ? intval($post['store_status']) : 1,
                'store_province' => !empty($post['store_province']) ? intval($post['store_province']) : 1,
                'store_city' => !empty($post['store_city']) ? intval($post['store_city']) : 2,
                'store_area' => !empty($post['store_area']) ? intval($post['store_area']) : 3,
                'store_address' => $post['store_address'],
                'store_business' => $post['store_business'],
                'store_logo' => !empty($post['store_logo']) ? $post['store_logo'] : '',
                'store_coverpic' => !empty($post['store_coverpic']) ? $post['store_coverpic'] : '',
                'store_latitude' => !empty($storePoint[1]) ? $storePoint[1] : '',
                'store_longitude' => !empty($storePoint[0]) ? $storePoint[0] : '',
                'store_intro' => !empty($post['store_intro']) ? $post['store_intro'] : '',
                'update_time' => $this->times,
            ];
            $result = $this->verify_store_db->where($where)->update($update);
            if (!empty($result)) {
                $this->success('编辑成功', weapp_url('Verify/Verify/verify_store'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 查询门店
        $store = $this->verify_store_db->where($where)->find();
        $store['store_point'] = $store['store_longitude'] . ',' . $store['store_latitude'];
        // 加载数据
        $this->assign('store', $store);
        $this->assign('provinceList', get_province_list());
        $cityList = $this->region_db->field('id, name')->where(['parent_id' => intval($store['store_province'])])->select();
        $this->assign('cityList', $cityList);
        $areaList = $this->region_db->field('id, name')->where(['parent_id' => intval($store['store_city'])])->select();
        $this->assign('areaList', $areaList);
        return $this->fetch();
    }

    // 核销门店删除
    public function verify_store_del()
    {
        $storeID = input('del_id/a', []);
        $storeID = eyIntval($storeID);
        if (IS_AJAX_POST && !empty($storeID)) {
            // 删除统一条件
            $where = [
                'store_id' => ['IN', $storeID],
            ];
            $result = $this->verify_store_db->where($where)->delete(true);
            if (!empty($result)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    // 核销门店列表
    public function verify_staff()
    {
        // 查询条件
        $where = [];
        $param = input('param.');
        if (!empty($param['staff_status'])) $where['a.staff_status'] = intval($param['staff_status']);
        if (!empty($param['keywords'])) $where['a.staff_name|a.staff_phone'] = ['like', "%{$param['keywords']}%"];

        // 查询门店
        $count = $this->verify_staff_db->alias('a')->where($where)->join('__USERS__ b', 'a.users_id = b.users_id')->count();
        $pageObj = new Page($count, config('paginate.list_rows'));
        $field = 'a.*, b.nickname, b.username, b.head_pic, c.store_name';
        $staff = $this->verify_staff_db->alias('a')
            ->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id')
            ->join('__WEAPP_VERIFY_STORE__ c', 'a.store_id = c.store_id')
            ->order('a.staff_id desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();
        foreach ($staff as $key => $value) {
            if (empty($value['nickname'])) $staff[$key]['nickname'] = $value['username'];
        }
        // 加载数据
        $this->assign('staff', $staff);
        $this->assign('pageObj', $pageObj);
        $this->assign('pageStr', $pageObj->show());
        return $this->fetch();
    }

    // 核销门店列表
    public function verify_staff_add()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            // 数据验证
            $validate = [
                ['field' => 'store_id', 'name' => '请选择所属门店'],
                ['field' => 'users_id', 'name' => '请选择核销会员'],
                ['field' => 'staff_name', 'name' => '请输入核销员名称'],
                ['field' => 'staff_phone', 'name' => '请输入核销员手机'],
            ];
            $this->validatePost($validate, $post);

            // 添加门店
            $insert = [
                'users_id' => intval($post['users_id']),
                'store_id' => intval($post['store_id']),
                'staff_name' => $post['staff_name'],
                'staff_phone' => $post['staff_phone'],
                'staff_status' => !empty($post['staff_status']) ? intval($post['staff_status']) : 1,
                'add_time' => $this->times,
                'update_time' => $this->times,
            ];
            $result = $this->verify_staff_db->insert($insert);
            if (!empty($result)) {
                $this->success('添加成功', weapp_url('Verify/Verify/verify_staff'));
            } else {
                $this->error('添加失败');
            }
        }

        // 核销门店列表
        $where = [
            'store_status' => 1,
        ];
        $storeList = $this->verify_store_db->where($where)->order('store_id desc')->select();
        $this->assign('storeList', $storeList);

        return $this->fetch();
    }

    // 核销门店列表
    public function verify_staff_edit()
    {
        $staff_id = input('param.staff_id/d', 0);
        $validate = [
            ['field' => 'staff_id', 'name' => '请选择编辑的核销员'],
        ];
        $this->validatePost($validate, ['staff_id'=>$staff_id]);

        // 查询条件
        $where = [
            'staff_id' => $staff_id
        ];

        if (IS_AJAX_POST) {
            $post = input('post.');
            // 数据验证
            $validate = [
                ['field' => 'store_id', 'name' => '请选择所属门店'],
                ['field' => 'users_id', 'name' => '请选择核销会员'],
                ['field' => 'staff_name', 'name' => '请输入核销员名称'],
                ['field' => 'staff_phone', 'name' => '请输入核销员手机'],
            ];
            $this->validatePost($validate, $post);

            // 编辑门店
            $update = [
                'users_id' => intval($post['users_id']),
                'store_id' => intval($post['store_id']),
                'staff_name' => $post['staff_name'],
                'staff_phone' => $post['staff_phone'],
                'staff_status' => !empty($post['staff_status']) ? intval($post['staff_status']) : 1,
                'update_time' => $this->times,
            ];
            $result = $this->verify_staff_db->where($where)->update($update);
            if (!empty($result)) {
                $this->success('编辑成功', weapp_url('Verify/Verify/verify_staff'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 查询核销职员
        $field = 'a.*, b.nickname, b.username, b.head_pic, c.store_name';
        $staff = $this->verify_staff_db->alias('a')
            ->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id')
            ->join('__WEAPP_VERIFY_STORE__ c', 'a.store_id = c.store_id')
            ->find();
        $staff['head_pic'] = get_head_pic($staff['head_pic']);
        $staff['nickname'] = !empty($staff['nickname']) ? $staff['nickname'] : $staff['username'];
        // 加载数据
        $this->assign('staff', $staff);

        // 核销门店列表
        $where = [
            'store_status' => 1,
        ];
        $storeList = $this->verify_store_db->where($where)->order('store_id desc')->select();
        $this->assign('storeList', $storeList);
        return $this->fetch();
    }

    // 核销员删除
    public function verify_staff_del()
    {
        $storeID = input('del_id/a', []);
        $storeID = eyIntval($storeID);
        if (IS_AJAX_POST && !empty($storeID)) {
            // 删除统一条件
            $where = [
                'staff_id' => ['IN', $storeID],
            ];
            $result = $this->verify_staff_db->where($where)->delete(true);
            if (!empty($result)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('参数有误');
    }

    // 地图地址选择
    public function select_map()
    {
        $editor = tpSetting('editor');
        $editor_bdmap_ak = !empty($editor['editor_bdmap_ak']) ? $editor['editor_bdmap_ak'] : '';
        $this->assign('editor_bdmap_ak', $editor_bdmap_ak);

        return $this->fetch();
    }

    // 核销员选择指定会员
    public function select_users()
    {
        // 查询条件
        $users_ids = $this->verify_staff_db->column('users_id');
        $where = [
            'is_del' => 0,
            'users_id' => ['NOT IN', $users_ids],
        ];
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $where['username|nickname'] = ['LIKE', "%{$keywords}%"];

        // 查询数据
        $count = Db::name('users')->where($where)->count();
        $pageObj = new Page($count, config('paginate.list_rows'));
        $field = 'users_id, username, nickname, head_pic';
        $list = Db::name('users')->field($field)->where($where)->limit($pageObj->firstRow . ',' . $pageObj->listRows)->order('users_id desc')->select();
        foreach ($list as $key => $value) {
            $list[$key]['head_pic'] = get_head_pic($value['head_pic']);
        }
        $this->assign('list', $list);
        $this->assign('pager', $pageObj);
        $this->assign('pageStr', $pageObj->show());

        return $this->fetch();
    }

    // 数据验证
    private function validatePost($validateArr = [], $post = [])
    {
        foreach ($validateArr as $value) {
            if (empty($post[$value['field']])) $this->error($value['name']);
        }
        return true;
    }

}